package com.alan.api.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.validation.BindingResult;

import javax.servlet.ServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Alan on 17-10-12
 */
//@Aspect
//@Order(-9)
//@Component
@Slf4j
public class AopWebLogConfig {

    @Pointcut("execution(* com.alan.api.web.*.*(..))")
    public void aopLogPointcut(){}

    @Before(value = "aopLogPointcut()")
    public void webBeforLog(JoinPoint joinPoint){
        String str = joinPoint.toLongString();
        String temp = str.subSequence("execution(".length(),str.length()-1).toString();
        String[] arrs = temp.split(" ");
        String methodName = arrs[arrs.length-1];
        if(log.isDebugEnabled()){
            log.debug("API请求方法：{}", methodName);
            Object[] args = joinPoint.getArgs();
            Map<String,String> argsMap = new HashMap<>();
            for (int i = 0; i < args.length; i++) {
                if(args[i] instanceof ServletRequest
                    || args[i] instanceof BindingResult){
                    continue;
                }
                argsMap.put("args-"+(i+1),JSON.toJSONString(args[i]));
            }
            log.debug("API请求参数：{}", JSON.toJSONString(argsMap));
       }

    }

    /**
     * 在方法正常执行通过之后执行的通知叫做返回通知
     * 可以返回到方法的返回值 在注解后加入returning
     * @param joinPoint
     */
    @AfterReturning(value = "aopLogPointcut()",returning="result")
    public void webAfterLog(JoinPoint joinPoint,Object result){
        String str = joinPoint.toLongString();
        String temp = str.subSequence("execution(".length(),str.length()-1).toString();
        String[] arrs = temp.split(" ");
        String methodName = arrs[arrs.length-1];
        if(log.isDebugEnabled()){
            log.debug("API返回方法：{}", methodName);
            log.debug("API返回参数：{}", JSON.toJSONString(result));
        }
    }

}
